package com.hcr.action;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;

import com.hcr.commons.IsAdmin;
import com.hcr.commons.PasswordToMD5;
import com.hcr.model.Role;
import com.hcr.model.User;
import com.hcr.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Component("loginAction")
public class LoginAction extends ActionSupport implements ModelDriven<User>{
	/**
	 * 
	 */
	private static final long serialVersionUID = 2287232429523671355L;
	private UserService userService;
	private User user=new User();
	public UserService getUserService() {
		return userService;
	}
	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public String login(){
		HttpServletRequest request=ServletActionContext.getRequest();
		String code=request.getParameter("code");
		String sessionCode = (String) request.getSession().getAttribute("session_vcode");
		if(!code.equalsIgnoreCase(sessionCode)){
			return "login";
		}
		user.setPassword(PasswordToMD5.MD5(this.user.getPassword()));
		List<User> list=this.userService.findByIdAndPassword(user.getId(), user.getPassword());
		if(!list.isEmpty()){
			ActionContext context=ActionContext.getContext();
			Map<String, Object> session = context.getSession();
			User user=list.iterator().next();
			session.put("user",user);          //将查询到的user放入session中保存
			if(IsAdmin.isAdmin()){
				return "success";
			}else{
				return "user-success";
			}
			
		}
		return "login";
	}
		

		
	
	public User getModel() {
		return this.user;
	}
}
